#!/usr/bin/python
# -*- coding: UTF-8 -*-

from requests import get
from requests_html import HTML
from urllib.parse import unquote as Url_Decode
from os.path import dirname, abspath
import random
import linecache
import sys

def Random_Agent():
	path = dirname(dirname(abspath(__file__))) + '/../data/user_agents.txt'
	random_index = random.randrange(1, 4275, 1) 
	random_user_agent = linecache.getline(r''+path, random_index)
	random_user_agent = random_user_agent.replace("\n","")
	return random_user_agent

def Google_Search(querystring,num = 100):
	print("[*] INFO: Searching %s" % querystring)
	url = "https://www.google.com/search?num="+str(num)+"&filter=0&q=" + querystring
	headers = {'user-agent': Random_Agent(),'referer':'https://www.google.com/'}
	response = get(url, headers = headers)
	search_result = response.content.decode('ISO-8859-1')
	return search_result

def Search_Result_Url(search_result):
	search_result = Url_Decode(search_result)
	html = HTML(html=search_result)
	links = [i for i in html.absolute_links]
	index = 1
	while index < len(links):
		if 'google' in links[index-1] or 'Google' in links[index-1] or 'example.org' in links[index-1] or 'youtube' in links[index-1]:
			links.remove(links[index-1])
			index = index -1
		index = index + 1
	print("[*] INFO: Google Searching Completed ")
	return links

def Search(querystring,num = 100):
	print("[*] INFO: Searching Start ...... Please Wait......")
	return Search_Result_Url(Google_Search(querystring,num))   # Return a list of Search Result URL

def main():
	try:
		querystring = sys.argv[1]
		num = sys.argv[2]
	except IndexError:
		print("[!] ERROR: Usage: $python[3] GoogleSearch.py QueryString NumberOfResult(default 100)")
		exit()
	link_list = Search(querystring,num)
	for i in link_list:
		print(i)

if __name__ == '__main__':
	main()